﻿using System;
using System.Threading;
using System.Web.Mvc;

namespace Motar.Web.Mvc
{
    
    /// <summary>
    /// 
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
    public abstract class LocalizeAttributeBase : ActionFilterAttribute
    {

        /// <summary>
        /// 
        /// </summary>
        public const string LocaleRouteSegment = "locale";

        /// <summary>
        /// 
        /// </summary>
        private readonly object _typeId = new object();

        /// <summary>
        /// 
        /// </summary>
        public override object TypeId
        {
            get { return _typeId; }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            string locale;

            try
            {
                locale = filterContext.RouteData.Values[LocaleRouteSegment].ToString();

                Apply(locale); Save(locale);

                return;
            }
            catch { }

            try
            {
                locale = Load(); Apply(locale);

                return;
            }
            catch { }

            try
            {
                locale = Localization.Current.DefaultLocale;

                Apply(locale); Save(locale);
            }
            catch { }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="locale"></param>
        protected virtual void Apply(string locale)
        {
            Thread.CurrentThread.CurrentUICulture = Localization.Current.Resolve(locale);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="culture"></param>
        protected abstract void Save(string locale);

        /// <summary>
        /// 
        /// </summary>
        protected abstract string Load();
    }
}
